// pages/cart/list/list.js
import {CartModel} from '../../../model/cart'
import {Tools} from '../../../utils/tools'
import { config } from '../../../config'
var cart = new CartModel()
var tools = new Tools()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    number:0,
    cartList:[],
    isAllCart:false,
    allAmount:0.0,
    cartIdList:[],
    modelList:[],
  },

  payAction(){
    if (this.data.cartIdList.length>0) {
      console.log(tools.listTostring(this.data.cartIdList))
      var data = {}
      data.modelList = this.data.modelList
      data.ids = tools.listTostring(this.data.cartIdList)
      data.allAmount = this.data.allAmount
      wx.navigateTo({
        url: '../send/send',
        success: function(res) {
          res.eventChannel.emit('detailInfo', data)
        }
      })
    }else{
      wx.showToast({
        title: '没有选择商品哦',
        icon: "none",
      })
    }
  },

  setAllCart(){
    config.cartList = []
    if (!this.data.isAllCart) {
      this.data.cartList.forEach(element => {
        config.cartList.push(element.id)
      });
    }
    this.setCart()
  },

  upData(){
    cart.list().then(
      res=>{
        if (res.code === 0) {
          if (res.data) {
            var number = 0;
            res.data.loseList.forEach(element => {
              number += element.quantity;
              element.cover = element.coverPicture.split(";;")[0]
            });
            this.setData({
              cartList:res.data.loseList,
              number:number
            })
            this.setCart()
          }else{
            this.setData({
              cartList:[],
              number:0
            })
          }
          
        }
      }
    )
  },

  setCart(){
    var isAllCart = this.data.cartList.length>0 ? true : false
    var allAmount = 0.0
    var cartIdList = []
    var modelList = []
    this.data.cartList.forEach(element => {
      if (!tools.isCartList(element.id)) {
        isAllCart = false
      }else{
        cartIdList.push(element.id)
        modelList.push(element)
        allAmount += element.retailPrice * element.quantity
      }
      element.isCart = tools.isCartList(element.id)
    });
    this.setData({
      cartList: this.data.cartList,
      isAllCart: isAllCart,
      allAmount: allAmount,
      cartIdList: cartIdList,
      modelList: modelList,
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.upData()
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})